#ifndef __UGEN_MAIN_C__
#define __UGEN_MAIN_C__
#include "ugen_feature.h"
#include "ugen_main.h"
#include "ugen_business.h"

uint64_t nowtime = 0x00;

/* 打印uart串口数据 */
int TRACE_BINARY(uint8_t *data, uint32_t len)
{
    for (int i = 0; i < len; i++)
    {
        printf(" %02x", *(data + i));
    }
    printf("  <end> \n");
    return 0;
}

/* LRC校验 */
uint16_t check_sum(uint8_t *data, uint8_t len)
{
    if ((data == NULL) || (len == 0))
        return NULL;
    uint8_t sum = 0x00;
    for (uint8_t i = 3; i < len; i++)
    {
        sum += data[i];
    }
    sum = 0x100 - (sum % 0x100);
    LOG_TRACE("check_sum: sum = 0x%x", sum);
    return sum;
}

/* 发送uart指令 */
int ugen_uart_send(unsigned char *data, int len)
{
    LOG_TRACE("ugen_uart_send : \n");
    TRACE_BINARY(data, len);
    return hfilop_uart_send_data(data, len);
}

/* 初始化 */
int lock_event_clean()
{
    LOG_TRACE("do_awss_reset\n");
    do_awss_reset();
    return 0;
}

/* 进入配网 */
void HAL_ugen_start_ap_config(uint8_t *data, uint8_t len)
{
    LOG_TRACE("HAL_ugen_start_ap_config\n");

    lock_event_clean(); //解除app界面设备
    // do_awss_reboot();//不解除app界面设备
    //do_awss_ble_start();
    //smart_ble_config();
    //do_awss_reboot();
    //lock_event_clean();
    //linkkit_key_process();
    // device_start_awss();
    // do_awss();
    // do_awss_active();
    //ugen_smart_config();
}

/* 配网 */
extern int awss_clear_reset(void);
uint8_t ugen_start_ap_config(uint8_t *data, uint32_t len)
{
    LOG_TRACE("ugen_start_ap_config=============\n");
    // uint8_t uart_send_data[5] = {MODEL_CMD_HEAD, 0xF9, 0x02, 0x03, 0x04};
    // ugen_uart_send(uart_send_data, 5);
    // aos_msleep(100);
    HAL_ugen_start_ap_config(data, len);
    return 0;
}

/* 获取网络状态 */
uint8_t ugen_get_wifi_state(void)
{
    switch (get_net_state())
    {
    case UNKNOW_STATE: //模组启动完成
        return 1;
    case WAITINGCONFIG: //模组待配网
        return 2;
    case CONNECT_CLOUD_SUCCESSED: //模组已配网
        return 3;
    case UNCONFIGED: //WIFI正处于配网状态，进入配网
        return 4;
    case CONNECT_CLOUD_SUCCESS: //WIFI连上云端,联网成功
        return 5;
    case CONNECT_AP_FAILED:    //WIFI未连上路由器，配网失败
    case CONNECT_CLOUD_FAILED: //WIFI连上路由器未连上云端，配网失败
        return 6;
    default:
        break;
    }
}

/* 回复配网状态 */
void ugen_wifi_state_reply(uint8_t *data, uint8_t len)
{
    uint8_t reply_buf[5] = {MODEL_CMD_HEAD, 0xFC, 0x02, 0x03, 0x01};
    reply_buf[4] = ugen_get_wifi_state();

    reply_buf[1] = check_sum(reply_buf, 5);
    ugen_uart_send(reply_buf, 5);

    printf("check-CONNECT_CLOUD_SUCCESS\n");
    if (reply_buf[4] == 5)
    {
        set_net_state(CONNECT_CLOUD_SUCCESSED); //配网成功，状态置为已配网；
        uint8_t state_buf[5] = {MODEL_CMD_HEAD, 0xFC, 0x02, 0x10, 0x01};
        state_buf[1] = check_sum(state_buf, 5);
        aos_msleep(200); //两条下发间隔太短，mcu无法分辨，适当进行延时；
        ugen_uart_send(state_buf, 5);
    }
    else if (reply_buf[4] == 6)
    {
        set_net_state(WAITINGCONFIG); //配网失败，状态置为待配网；
    }
}

/* 初始化 */
void ugen_reset_start(uint8_t *data, uint32_t len)
{
    printf("reset_start\n");
    uint8_t reset_buf[5] = {MODEL_CMD_HEAD, 0xFC, 0x02, 0x04, 0x01};
    check_sum(reset_buf, 5);
    ugen_uart_send(reset_buf, 5);
    lock_event_clean();
}

/* 心跳回复 */
void hertbeat_reply(uint8_t *data, uint32_t len)
{
    uint8_t reply_buf[5] = {MODEL_CMD_HEAD, 0xFC, 0x02, 0x05, 0x01};
    reply_buf[1] = check_sum(reply_buf, 5);
    ugen_uart_send(reply_buf, 5);
}

//请求更新时间戳，会自动和云端同步时间
extern void ntp_timer_update(const char *str);
extern uint64_t local_update_timestamp(void);
uint64_t sync_timeStamp_tiemr_cb(void)
{
    uint64_t timeStamps = 0;
    uint64_t time = 0;
    if (get_net_state() == CONNECT_CLOUD_SUCCESS) //如果联网，通过网络更新时间
    {
        linkkit_ntp_time_request(ntp_timer_update);
    }
    time = local_update_timestamp(); //本地获取时间
    timeStamps = nowtime + time;
    printf("sync_timeStamp_tiemr_cb = %d", (uint32_t)timeStamps);
    return timeStamps;
}

/* 发送时间戳 */
void ugen_send_timeStamp(uint8_t *data, uint32_t len)
{
    uint8_t wifi_timestamp[8] = {MODEL_CMD_HEAD, 0xFC, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00};
    uint64_t timeStamp = sync_timeStamp_tiemr_cb();
    wifi_timestamp[4] = (timeStamp & 0xFF000000) >> 24;
    wifi_timestamp[5] = (timeStamp & 0x00FF0000) >> 16;
    wifi_timestamp[6] = (timeStamp & 0x0000FF00) >> 8;
    wifi_timestamp[7] = (timeStamp & 0x000000FF);
    wifi_timestamp[1] = check_sum(wifi_timestamp, 8);

    ugen_uart_send(wifi_timestamp, 8);
}

/* 产测，返回0成功 */
int ugen_factory_find_ap(uint8_t cmd)
{
    /* scan wifi */
    int ret = 0;
    uint32_t scan_time = 5000;
    ap_scan_info_t scan_result;
    int ap_scan_result = -1;
    // start ap scanning for default 3 seconds
    memset(&scan_result, 0, sizeof(ap_scan_info_t));
    ap_scan_result = awss_apscan_process(&scan_time, FACTORY_TEST_AP_SSID, &scan_result);
    switch (cmd)
    {
    case 1: //扫描到wifi成功
    {
        if ((ap_scan_result == 0) && (scan_result.found))
        {
            LOG("[FACTORY]scan factory AP result = %d", scan_result.found);
            int rssi = (scan_result.rssi > 0) ? scan_result.rssi : (0 - scan_result.rssi);
            printf("rssi = %d\n", rssi);
            return rssi;
        }
        else
        {
            ret = -1;
        }
        break;
    }
    case 2: //连接wifi，连接上会发送联网成功指令
    {
        LOG("[FACTORY]s connect wifi\n");
        if (scan_result.rssi < -60)
        {
            return -1;
        }
        netmgr_ap_config_t config;
        strncpy(config.ssid, FACTORY_TEST_AP_SSID, sizeof(config.ssid) - 1);
        strncpy(config.pwd, FACTORY_TEST_AP_PSW, sizeof(config.pwd) - 1);
        netmgr_set_ap_config(&config);

        // netmgr_start(true);
        set_net_state(UNCONFIGED);
        extern int awss_stop(void);
        awss_stop();

        extern void check_factory_mode(void);
        check_factory_mode();
        // netmgr_init();
        // extern int awss_start(void);
        // awss_start();
        //check_factory = 1;
        break;
    }
    /*
        case 3://蓝牙产测
        {
            测wifi就等于硬件RF测试了，没有必要再测蓝牙，如果一定要测蓝牙，可以开发手机的APP，不停的去连接蓝牙（sdk暂时没有该功能）。
        }
        */
    default:
        ret = -1;
    }

    return ret;
}

/* 产测,ret等于0产测成功 */
int ugen_pt_start(uint8_t cmd)
{
    //int ret = scan_factory_ap();
    int ret = ugen_factory_find_ap(cmd);
    //printf("\nfactory_test start %d\n",ret);
    return ret;
}

/* 产测 */
void ugen_factory_test(uint8_t *data, uint32_t len)
{
    uint8_t cmd = data[4];
    int ret = ugen_pt_start(cmd);
    if (cmd == 2)
        return;
    uint8_t factory_buf[6] = {MODEL_CMD_HEAD, 0x03, 0x02, FACTORY, 0x01, 0x00};
    if (ret >= 0)
        factory_buf[5] = ret;
    else
        factory_buf[4] = 0x00; //产测失败,,0x01//产测成功
    factory_buf[1] = check_sum(factory_buf, 6);
    ugen_uart_send(factory_buf, 6);
}

/* 自检超时的判断 */
void check_is_test(void)
{
    FACTORY_TEST_FLAG = 0;
    uint8_t factory_buf[6] = {MODEL_CMD_HEAD, 0x03, 0x02, FACTORY, 0x01, 0x00};
    factory_buf[4] = 0x00; //产测失败,0x01//产测成功
    factory_buf[1] = check_sum(factory_buf, 6);
    ugen_uart_send(factory_buf, 6);
    netmgr_clear_ap_config();
    aos_timer_stop(&wifi_connect_timer);
    aos_timer_free(&wifi_connect_timer);
    HAL_Reboot();
}

#endif //__UGEN_MAIN_C__